package com.yanqu.road.server.manager.cookboy;

import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.cookboy.process2.*;
import com.yanqu.road.entity.activity.cookboy.process3.*;
import com.yanqu.road.entity.player.UserBaseInfo;
import com.yanqu.road.logic.bussiness.cross.CrossCookBoyBussiness;
import com.yanqu.road.logic.pb.PlayerBasePb;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.pb.cookboy.CookBoyProto;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.manager.user.CrossUserMgr;
import com.yanqu.road.server.pb.cookboy.CrossCookBoyPb;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.date.DateHelper;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class CrossCookBoy3 {

    private Logger logger = LogManager.getLogger(CrossCookBoy3.class.getName());

    private Map<Integer,Object> lockMap = new ConcurrentHashMap<>();

    private ActivityInfo activityInfo;

    private Map<Long, CookBoyUpUser> cookerMap = new ConcurrentHashMap<>();
    private List<CookBoyUpUser> needInsertUserList = new ArrayList<>();

    //用户id场次no
    private Map<Long,Map<Integer, CookBoy3Table>> cookBoyTableMap = new ConcurrentHashMap<>();

    private List<CookBoyUpUser> needSyncCookerList = new ArrayList<>();

    private List<CookBoy3Table> syncTableList = new ArrayList<>();

    private List<CookBoy3Table> syncOpenList = new ArrayList<>();

    private List<CookBoy3Table> needInsertTableList = new ArrayList<>();
    private List<CookBoy3Table> needUpdateTableList = new ArrayList<>();

    public int getActivityId(){
        return activityInfo.getActivityId();
    }

    public ActivityInfo getActivityInfo(){
        return activityInfo;
    }

    public String getCookBoy3BanquetTimes(String param){
        long homeUserId = Long.valueOf(param);
        if(cookBoyTableMap.containsKey(homeUserId)){
            return String.valueOf(cookBoyTableMap.get(homeUserId).size());
        }
        return "0";
    }

    public String getCookBoy3BanquetUserCount(String param){
        long homeUserId = Long.valueOf(param);
        if(cookBoyTableMap.containsKey(homeUserId)){
            int userCount = 0;
            for(CookBoy3Table cookBoy3Table :new ArrayList<>( cookBoyTableMap.get(homeUserId).values())){
                userCount += cookBoy3Table.getCookBoy3JoinerMap().size();
            }
            return String.valueOf(userCount);
        }
        return "0";
    }

    private Map<Integer,Long> getPageJoinMap(Map<Integer,Long> joinerMap,int page,int num){
        Map<Integer,Long> resMap = new ConcurrentHashMap<>();
        int count = joinerMap.size();
        int index = (page - 1) * num;
        int resCount = 0;
        for(;index < count + num;index++){
            if(resCount++ == num){
                break;
            }
            if(joinerMap.size() > index){
                //joinerMap的key是位置，按照1开始
                Long userId = joinerMap.get(index + 1);
                resMap.put(index,userId);
            }else{
                break;
            }
        }
        return resMap;
    }

    public void getBanquetJoiner(long serverId,long userId,long homeUserId,int banquetId,int page,int num){
        if(page == 0){
            page = 1;
        }
        if(num == 0 || num > 100){
            num = 100;
        }
        CookBoyProto.CookBoy3BanquetJoinerRespMsg.Builder msg = CookBoyProto.CookBoy3BanquetJoinerRespMsg.newBuilder();
        msg.setRet(0);
        msg.setActivityId(getActivityId());
        msg.setHomeUserId(homeUserId);
        msg.setBanquetId(banquetId);
        if(cookBoyTableMap.containsKey(homeUserId) && cookBoyTableMap.get(homeUserId).containsKey(banquetId)){
            CookBoy3Table cookBoy3Table = cookBoyTableMap.get(homeUserId).get(banquetId);
            Map<Integer,Long> joinerMap = cookBoy3Table.getCookBoy3JoinerMap();
            Map<Integer,Long> resMap = getPageJoinMap(joinerMap,page,num);
            for(Integer pos : resMap.keySet()){
                CookBoyProto.CookBoy3BanquetJoinerTempMsg.Builder tempMsg = CookBoyProto.CookBoy3BanquetJoinerTempMsg.newBuilder();
                tempMsg.setUserId(resMap.get(pos));
                tempMsg.setPos(pos);
                UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(resMap.get(pos));
                if(userBaseInfo == null){
                    continue;
                }
                tempMsg.setUserInfo(PlayerBasePb.parsePlayerBaseTempMsg(userBaseInfo));
                msg.addJoinerList(tempMsg);
            }
            msg.setUserCount(joinerMap.size());
        }
        YanQuMessage pbOpenerMsg = YanQuMessageUtils.buildMessage(Protocol.U_COOK_BOY3_GET_BANQUET_MEMBER, msg);
        MessageHelper.sendPacket(serverId, userId, pbOpenerMsg);
    }

    public void getUserBanquet(long serverId, long userId,long homeUserId){
            CookBoyProto.CookBoy3GetUserBanquetRespMsg.Builder msg = CookBoyProto.CookBoy3GetUserBanquetRespMsg.newBuilder();
            msg.setRet(0);
            if(cookBoyTableMap.containsKey(homeUserId)){
                ArrayList<CookBoy3Table> cookBoy3Tables = new ArrayList<>(cookBoyTableMap.get(homeUserId).values());
                cookBoy3Tables.sort(Comparator.comparingLong(CookBoy3Table::getOpenTime));
                Collections.reverse(cookBoy3Tables);
                int num = 0;
                for(CookBoy3Table cookBoy3Table : cookBoy3Tables){
                    CookBoyProto.CookBoy3BanquetTempMsg.Builder tempMsg = CookBoyProto.CookBoy3BanquetTempMsg.newBuilder();
                    tempMsg.setBanquetId(cookBoy3Table.getNo());
                    tempMsg.setOpenItemId(cookBoy3Table.getOpenItemId());
                    tempMsg.setOpenTime((int)(cookBoy3Table.getOpenTime()/1000));
                    tempMsg.setUserCount(cookBoy3Table.getCookBoy3JoinerMap().size());
                    tempMsg.setIntegral(cookBoy3Table.getIntegral());
                    if (System.currentTimeMillis() - cookBoy3Table.getOpenTime() >= 3600*1000) {
                        tempMsg.setSelfJoin(false);
                    }else {
                        tempMsg.setSelfJoin(cookBoy3Table.getCookBoy3JoinerMap().containsValue(userId));
                    }
                    msg.addBanquetList(tempMsg);
                    num++;
                    if (num >= 50) {
                        break;
                    }
                }
            }
            YanQuMessage pbOpenerMsg = YanQuMessageUtils.buildMessage(Protocol.U_COOK_BOY3_GET_USER_BANQUET, msg);
            MessageHelper.sendPacket(serverId, userId, pbOpenerMsg);
    }

    public CookBoy3BanquetReward getBanquetReward(long userId, int banquetId){
        CookBoy3BanquetReward cookBoy3BanquetReward = new CookBoy3BanquetReward();
        if(!cookBoyTableMap.containsKey(userId)){
            cookBoy3BanquetReward.setRet(GameErrorCode.E_COOK_BOY3_USER_NOT_MATCH);
            return cookBoy3BanquetReward;
        }
        CookBoy3Table cookBoy3Table = cookBoyTableMap.get(userId).get(banquetId);
        if(null == cookBoy3Table){
            cookBoy3BanquetReward.setRet(GameErrorCode.E_COOK_BOY3_BANQUET_NOT_FOUND);
            return cookBoy3BanquetReward;
        }
        if(cookBoy3Table.getOverTime() == 0){
            cookBoy3BanquetReward.setRet(GameErrorCode.E_COOK_BOY3_BANQUET_NOT_OVER);
            return cookBoy3BanquetReward;
        }
        int integralId = CrossCookBoyActivityMgr.getCookBoy3IntegralItemId(activityInfo.getActivityId());
        cookBoy3BanquetReward.setReward(integralId + "=" + cookBoy3Table.getIntegral());
        cookBoy3BanquetReward.setIntegral(cookBoy3Table.getIntegral());
        cookBoy3BanquetReward.setUserCount(cookBoy3Table.getCookBoy3JoinerMap().size());
        cookBoy3BanquetReward.setOpenItemId(cookBoy3Table.getOpenItemId());
        return cookBoy3BanquetReward;
    }

    private CookBoy3EndBanquet endTable(CookBoy3Table cookBoy3Table){
        CookBoy3EndBanquet cookBoy2EndBanquet = null;
        if(cookBoy3Table.getOverTime() == 0){
            cookBoy3Table.setOverTime(System.currentTimeMillis());
            cookBoy2EndBanquet = new CookBoy3EndBanquet();

            //结束了加上没坐完的自动填充机器人那部分积分
            /*CookBoy3OpenItem cookBoy3OpenItem = CrossCookBoyActivityMgr.getCookBoy3OpenItem(getActivityId(),cookBoy3Table.getOpenItemId());
            int needAddNum = cookBoy3OpenItem.getEatNum() - cookBoy3Table.getCookBoy3JoinerList().size();
            if(needAddNum > 0){
                long addIntegral = cookBoy3OpenItem.getIntegral() * needAddNum * CrossCookBoyActivityMgr.getCookBoy3RobotAdd(getActivityId()) / 1000;
                CookBoyProto.CrossCookBoy3RobotJoinBanquetMsg.Builder msg = CookBoyProto.CrossCookBoy3RobotJoinBanquetMsg.newBuilder();
                msg.setRet(0);
                msg.setActivityId(getActivityId());
                msg.setHomeUserId(cookBoy3Table.getUserId());
                msg.setIntegral(addIntegral);
                msg.setBanquetItemId(cookBoy3Table.getOpenItemId());
                YanQuMessage pbOpenerMsg = YanQuMessageUtils.buildMessage(Protocol.S_CROSS_COOK_BOY3_ROBOT_JOIN, msg);
                MessageHelper.sendChannelPacket(cookBoy3Table.getServerId(), cookBoy3Table.getUserId(), pbOpenerMsg);
                cookBoy3Table.setIntegral(cookBoy3Table.getIntegral() + addIntegral);
            }*/
            synchronized (needUpdateTableList){
                if(!needUpdateTableList.contains(cookBoy3Table)){
                    needUpdateTableList.add(cookBoy3Table);
                }
            }
        }

        return cookBoy2EndBanquet;
    }

    private void tableCheck(){
        for(Map<Integer, CookBoy3Table> userTableMap : cookBoyTableMap.values()){
            for(CookBoy3Table cookBoy3Table : userTableMap.values()){
                if(cookBoy3Table.getOverTime() != 0)continue;

                    CookBoy3EndBanquet eatTableRes = null;
                    CookBoy3OpenItem cookBoy3OpenItem = CrossCookBoyActivityMgr.getCookBoy3OpenItem(getActivityId(),cookBoy3Table.getOpenItemId());
                    if(cookBoy3OpenItem == null){
                        continue;
                    }
                    //时间到了结束//座位坐满了结束
                    if(System.currentTimeMillis() - cookBoy3Table.getOpenTime() > cookBoy3OpenItem.getMinute() * 60 * 1000 ||
                            cookBoy3Table.getCookBoy3JoinerMap().size() >= cookBoy3OpenItem.getEatNum()){
                        synchronized (getBanquetLock(cookBoy3Table.getNo())){
                            eatTableRes = endTable(cookBoy3Table);
                        }
                    }
                    //不会结束，除非时间到了或者坐满了
                    /*if(!CrossCookBoyActivityMgr.isActivityMatchTime(activityInfo)){
                        eatTableRes = endTable(cookBoy3Table);
                    }*/
                    if(eatTableRes != null){
                        syncTableServer(cookBoy3Table);
                    }
                }
            }
    }

    //按照排名给桌子排下序
    private void rankToPos(){
        List<CookBoyUpUser> upUserList = new ArrayList<>(cookerMap.values());
        upUserList.sort(new PosSort());
        int rank = 1;
        for(CookBoyUpUser cookBoyUpUser : upUserList){
            cookBoyUpUser.setRank(rank);
            cookBoyUpUser.setPos(rank);
            rank++;
        }
    }

    public void setActivityInfo(ActivityInfo activityInfo){
        this.activityInfo = activityInfo;
    }

    //从大到小
    static class PosSort implements Comparator<CookBoyUpUser> {
        @Override
        public int compare(CookBoyUpUser o1, CookBoyUpUser o2) {
            if (o1.getLastScore() == o2.getLastScore()) {
                return 0;
            }
            if (o1.getLastScore() <= o2.getLastScore()) {
                return 1;
            }
            return -1;
        }
    }

    public void addPromotionUser(Map<Integer,Long> userMap){
        for(int rank : userMap.keySet()){
            long userId = userMap.get(rank);
            UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(userId);
            if(!cookerMap.containsKey(userId)){
                CookBoyUpUser cookBoyUp = new CookBoyUpUser();
                cookBoyUp.setActivityId(activityInfo.getActivityId());
                cookBoyUp.setServerId(userBaseInfo.getServerId());
                cookBoyUp.setUserId(userId);
                cookBoyUp.setPos(rank);
                cookBoyUp.setType(3);
                cookerMap.put(cookBoyUp.getUserId(),cookBoyUp);
                synchronized (needInsertUserList){
                    if(!needInsertUserList.contains(cookBoyUp)){
                        needInsertUserList.add(cookBoyUp);
                    }
                }
            }
        }
    }

    public void addPromotionUser(long serverId,List<CookBoyProto.CrossCookBoyWindUpCookerTempMsg> userListMsg){
        boolean sortFlag = false;
        for(CookBoyProto.CrossCookBoyWindUpCookerTempMsg tempMsg : userListMsg){
            long userId = tempMsg.getUserId();
            UserBaseInfo userBaseInfo = PlayerBasePb.parseToUserBaseInfo(tempMsg.getPlayerBaseData());
            CrossUserMgr.updateUserBaseInfo(userId,userBaseInfo);
            if(!cookerMap.containsKey(userId)){
                sortFlag = true;
                CookBoyUpUser cookBoyUpUser = new CookBoyUpUser();
                cookBoyUpUser.setActivityId(activityInfo.getActivityId());
                cookBoyUpUser.setServerId(serverId);
                cookBoyUpUser.setUserId(userId);
                //瞎鸡巴赋值一下，这里的位置顺序是按照积分排名的
                cookBoyUpUser.setPos(cookerMap.size() + 1);
                cookBoyUpUser.setType(3);
                if(tempMsg.getScore() != 0){
                    cookBoyUpUser.setLastScore(tempMsg.getScore());
                }
                cookBoyUpUser.setForbiddenSpoonList(new ArrayList<>());
                cookerMap.put(cookBoyUpUser.getUserId(),cookBoyUpUser);
                synchronized (needInsertUserList){
                    if(!needInsertUserList.contains(cookBoyUpUser)){
                        needInsertUserList.add(cookBoyUpUser);
                    }
                }
            }
        }
        if(sortFlag){
            rankToPos();
        }
    }

    private Object getBanquetLock(int no){
        if(!lockMap.containsKey(no)){
            synchronized (lockMap) {
                if (!lockMap.containsKey(no))
                    lockMap.put(no,new Object());
            }
        }
        return lockMap.get(no);
    }

    public int joinBanquet(long serverId,long joinUserId,long homeUserId,int banquetId){
     //   tableCheck();
            if(!cookBoyTableMap.containsKey(homeUserId)){
                return GameErrorCode.E_COOK_BOY3_USER_NOT_MATCH;
            }
            Map<Integer,CookBoy3Table> cookBoy3TableMap = cookBoyTableMap.get(homeUserId);
            if(!cookBoy3TableMap.containsKey(banquetId)){
                return GameErrorCode.E_COOK_BOY3_BANQUET_NOT_FOUND;
            }
            CookBoy3Table cookBoy3Table = cookBoy3TableMap.get(banquetId);
            CookBoy3OpenItem cookBoy3OpenItem = CrossCookBoyActivityMgr.getCookBoy3OpenItem(getActivityId(),cookBoy3Table.getOpenItemId());
            if(cookBoy3OpenItem == null){
                return GameErrorCode.E_COOK_BOY3_OPEN_BANQUET_ITEM_NOT_FOUND;
            }
            if(System.currentTimeMillis() > cookBoy3Table.getOpenTime() + cookBoy3OpenItem.getMinute() * 60 * 1000){
                return GameErrorCode.E_COOK_BOY3_BANQUET_OVER;
            }
            /*if(cookBoy3Table.getCookBoy3JoinerMap().size() >= cookBoy3OpenItem.getEatNum()){
                return GameErrorCode.E_COOK_BOY3_USER_JOIN_FULL;
            }*/
            /*if(!CrossCookBoyActivityMgr.isActivityMatchTime(activityInfo)){
                return GameErrorCode.E_COOK_BOY3_ACTIVITY_NOT_RUNNING;
            }*/
        int size = 0;
        synchronized (getBanquetLock(banquetId)){
            Map<Integer, Long> joinerMap = cookBoy3Table.getCookBoy3JoinerMap();
            if(joinerMap.containsValue(joinUserId)){
                return GameErrorCode.E_COOK_BOY3_TABLE_IS_JOIN;
            }
                joinerMap.put(joinerMap.size() + 1,joinUserId);
                cookBoy3Table.setCookBoy3JoinerMap(joinerMap);
                size = cookBoy3Table.getCookBoy3JoinerMap().size();
        }

            CookBoyProto.CrossCookBoy3JoinBanquetMsg.Builder msg = CookBoyProto.CrossCookBoy3JoinBanquetMsg.newBuilder();
            msg.setRet(0);
            msg.setActivityId(getActivityId());
            msg.setJoinerUserId(joinUserId);
            msg.setHomeUserId(homeUserId);
            msg.setBanquetItemId(cookBoy3Table.getOpenItemId());
            //发给开宴会的和参加宴会的人给他们加奖励和积分
            //1.宴会人满了就可以开下一场，但是时间还没到可以继续坐人，坐人只给参加者发奖励，不给开宴者家积分
            //或者在比赛时间才加积分
            if(size <= cookBoy3OpenItem.getEatNum() &&
                        CrossCookBoyActivityMgr.isActivityMatchTime(activityInfo) &&
                        CrossCookBoyActivityMgr.activityInTime(activityInfo)){
                synchronized (getBanquetLock(banquetId)) {
                    cookBoy3Table.setIntegral(cookBoy3Table.getIntegral()+cookBoy3OpenItem.getIntegral());
                }
                    YanQuMessage pbOpenerMsg = YanQuMessageUtils.buildMessage(Protocol.S_CROSS_COOK_BOY3_JOIN_OPENER, msg);
                    MessageHelper.sendPacket(cookBoy3Table.getServerId(), homeUserId, pbOpenerMsg);
                }
                YanQuMessage pbJoinerMsg = YanQuMessageUtils.buildMessage(Protocol.S_CROSS_COOK_BOY3_JOIN_JOINER, msg);
                MessageHelper.sendPacket(serverId, joinUserId, pbJoinerMsg);
                synchronized (needUpdateTableList){
                    if (!needUpdateTableList.contains(cookBoy3Table)) {
                        needUpdateTableList.add(cookBoy3Table);
                    }
                }
                synchronized (syncTableList){
                    if (!syncTableList.contains(cookBoy3Table)) {
                        syncTableList.add(cookBoy3Table);
                    }
                }
                synchronized (needSyncCookerList){
                    if(!needSyncCookerList.contains(cookerMap.get(homeUserId))){
                        needSyncCookerList.add(cookerMap.get(homeUserId));
                    }
            }
       // tableCheck();
        return 0;
    }

    private boolean isOpenTable(long homeUserId){


        Map<Integer, CookBoy3Table> tableMap = cookBoyTableMap.get(homeUserId);
        for(CookBoy3Table cookBoy3Table : tableMap.values()){
            CookBoy3EndBanquet eatTableRes = null;
            CookBoy3OpenItem cookBoy3OpenItem = CrossCookBoyActivityMgr.getCookBoy3OpenItem(getActivityId(),cookBoy3Table.getOpenItemId());
            if(cookBoy3OpenItem == null){
                continue;
            }
            if(System.currentTimeMillis() - cookBoy3Table.getOpenTime() > cookBoy3OpenItem.getMinute() * 60 * 1000 ||
                    cookBoy3Table.getCookBoy3JoinerMap().size() >= cookBoy3OpenItem.getEatNum()){
                synchronized (getBanquetLock(cookBoy3Table.getNo())){
                    eatTableRes = endTable(cookBoy3Table);
                }
            }
            //不会结束，除非时间到了或者坐满了
                    /*if(!CrossCookBoyActivityMgr.isActivityMatchTime(activityInfo)){
                        eatTableRes = endTable(cookBoy3Table);
                    }*/
            if(eatTableRes != null){
                syncTableServer(cookBoy3Table);
            }
         if(cookBoy3Table.getOverTime() == 0){
             return true;
         }
        }
        return false;
    }

    private CookBoy3Table initCookBoy3Banquet(long serverId,long userId,int itemId,int no){
        CookBoy3Table newOne = new CookBoy3Table();
        newOne.setActivityId(activityInfo.getActivityId());
        newOne.setServerId(serverId);
        newOne.setUserId(userId);
        newOne.setOpenItemId(itemId);
        newOne.setOpenTime(System.currentTimeMillis());
        newOne.setOverTime(0);
        newOne.setIntegral(0);
        newOne.setJoinerData("{}");
        newOne.setNo(no);

        return newOne;
    }

    private int getTableCount(){
        int count = 0;
        for(Map<Integer, CookBoy3Table> userMap : cookBoyTableMap.values()){
            count += userMap.size();
        }
        return count;
    }

    public void openBanquet(long serverId,long userId,int itemId){
     //   tableCheck();
        CookBoyProto.CrossCookBoy3OpenBanquetRespMsg.Builder msg = CookBoyProto.CrossCookBoy3OpenBanquetRespMsg.newBuilder();
        msg.setActivityId(getActivityId());
        msg.setUserId(userId);
        msg.setItemId(itemId);
        int ret = 0;
        if(!cookBoyTableMap.containsKey(userId)){
            cookBoyTableMap.put(userId,new ConcurrentHashMap<>());
        }
        if(isOpenTable(userId)){
            ret = GameErrorCode.E_COOK_BOY3_IS_OPEN_BANQUET;
        }
        if(ret == 0){
            CookBoy3Table newOne = initCookBoy3Banquet(serverId,userId,itemId, getTableCount() + 1);
            cookBoyTableMap.get(userId).put(newOne.getNo(),newOne);
            synchronized (needInsertTableList){
                if(!needInsertTableList.contains(newOne)){
                    needInsertTableList.add(newOne);
                }
            }
            synchronized (syncOpenList){
                syncOpenList.add(newOne);
            }
            synchronized (needSyncCookerList){
                if(!needSyncCookerList.contains(cookerMap.get(userId))){
                    needSyncCookerList.add(cookerMap.get(userId));
                }
            }
            syncTableServer(newOne);
            timeSyncBanquetOpenServer();
            timeSyncBanquetUserServer();
            msg.setBanquetId(newOne.getNo());
        }
        msg.setRet(ret);
        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_CROSS_COOK_BOY3_OPEN_BANQUET, msg);
        MessageHelper.sendPacket(serverId, userId, pbMsg);
    }

    //同步这个服参加了哪些人，用来判断是不是自己可以参加
    private List<Long> getServerAllUserIdList(long serverId,CookBoy3Table table){
        List<Long> resList = new ArrayList<>();
        for(long userId : new ArrayList<>(table.getCookBoy3JoinerMap().values())){
            UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(userId);
            if(userBaseInfo != null && userBaseInfo.getServerId() == serverId){
                resList.add(userId);
            }
        }
        return resList;
    }

    public void syncTableServer(CookBoy3Table newOne){
        for(long serverId : activityInfo.getServerIdList()){
            CookBoyProto.CrossCookBoy3TableSyncMsg.Builder respMsg = CookBoyProto.CrossCookBoy3TableSyncMsg.newBuilder();
            respMsg.setActivityId(getActivityId());
            CookBoyProto.CookBoy3CookerCrossTempMsg.Builder tempTableMsg = parseCookBoy3CookerCrossTempMsg(serverId,cookerMap.get(newOne.getUserId()).getRank(),newOne);
            if(tempTableMsg == null){
                continue;
            }
            respMsg.addTableList(tempTableMsg);
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_CROSS_COOK_BOY3_TABLE_SYNC, respMsg);
            MessageHelper.sendPacket(serverId, 0, pbMsg);
        }
    }

    public CookBoyProto.CookBoy3CookerCrossTempMsg.Builder parseCookBoy3CookerCrossTempMsg(long serverId,int rank,CookBoy3Table cookBoy3Table) {
        CookBoyProto.CookBoy3CookerCrossTempMsg.Builder tempTableMsg = CookBoyProto.CookBoy3CookerCrossTempMsg.newBuilder();
        UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(cookBoy3Table.getUserId());
        if(userBaseInfo == null){
            return null;
        }
        tempTableMsg.setUserInfo(PlayerBasePb.parsePlayerBaseTempMsg(userBaseInfo));
        tempTableMsg.setRank(rank);
        tempTableMsg.setUserId(cookBoy3Table.getUserId());
        CookBoy3OpenItem cookBoy3OpenItem = CrossCookBoyActivityMgr.getCookBoy3OpenItem(getActivityId(),cookBoy3Table.getOpenItemId());
        if(System.currentTimeMillis() - cookBoy3Table.getOpenTime() <= cookBoy3OpenItem.getMinute() * 60 * 1000){
            tempTableMsg.setOpenItemId(cookBoy3Table.getOpenItemId());
            tempTableMsg.setOpenTime((int)(cookBoy3Table.getOpenTime()/1000));
            tempTableMsg.setBanquetId(cookBoy3Table.getNo());
            tempTableMsg.setUserNum(cookBoy3Table.getCookBoy3JoinerMap().size());
            tempTableMsg.addAllUserLit(getServerAllUserIdList(serverId,cookBoy3Table));
        }else{
            tempTableMsg.setOpenItemId(0);
            tempTableMsg.setOpenTime(0);
            tempTableMsg.setBanquetId(0);
            tempTableMsg.setUserNum(0);
            tempTableMsg.addAllUserLit(new ArrayList<>());
        }
        tempTableMsg.setBanquetCount(getUserBanquetCount(cookBoy3Table.getUserId()));
        return tempTableMsg;
    }

    public void syncTableServer(List<CookBoy3Table> syncTableList){
        Map<Long,CookBoy3Table> needSync = new ConcurrentHashMap<>();
        for(CookBoy3Table cookBoy3Table : syncTableList){
            if(needSync.containsKey(cookBoy3Table.getUserId())){
                if(cookBoy3Table.getNo() > needSync.get(cookBoy3Table.getUserId()).getNo()){
                    needSync.put(cookBoy3Table.getUserId(),cookBoy3Table);
                }
            }else{
                needSync.put(cookBoy3Table.getUserId(),cookBoy3Table);
            }
        }
        for(long serverId : activityInfo.getServerIdList()){
            CookBoyProto.CrossCookBoy3TableSyncMsg.Builder respMsg = CookBoyProto.CrossCookBoy3TableSyncMsg.newBuilder();
            respMsg.setActivityId(getActivityId());
            for(CookBoy3Table one : needSync.values()){
                CookBoyProto.CookBoy3CookerCrossTempMsg.Builder tempTableMsg = parseCookBoy3CookerCrossTempMsg(serverId,cookerMap.get(one.getUserId()).getRank(),one);
                if(tempTableMsg == null){
                    continue;
                }
                respMsg.addTableList(tempTableMsg);
            }
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_CROSS_COOK_BOY3_TABLE_SYNC, respMsg);
            MessageHelper.sendPacket(serverId, 0, pbMsg);
        }
    }


    private CookBoy3Table getUserOpenBanquet(long homeUserId){
        if(!cookBoyTableMap.containsKey(homeUserId)){
            return null;
        }
        Map<Integer,CookBoy3Table> tableMap = cookBoyTableMap.get(homeUserId);
        CookBoy3Table returnTable = null;
        Map<Integer, CookBoy3OpenItem> cookBoy3OpenItemMap = new HashMap<>();
        for(CookBoy3Table table : tableMap.values()){
            if (System.currentTimeMillis() - table.getOpenTime() > 3600 * 1000) {
                continue;
            }
            CookBoy3OpenItem cookBoy3OpenItem  = cookBoy3OpenItemMap.get(table.getOpenItemId());
            if (cookBoy3OpenItem == null) {
                cookBoy3OpenItem   = CrossCookBoyActivityMgr.getCookBoy3OpenItem(getActivityId(),table.getOpenItemId());
                if (cookBoy3OpenItem != null) {
                    cookBoy3OpenItemMap.put(table.getOpenItemId(), cookBoy3OpenItem);
                }
            }
            if(cookBoy3OpenItem == null){
                continue;
            }
            if(System.currentTimeMillis() - table.getOpenTime() < cookBoy3OpenItem.getMinute() * 60 * 1000){
                //返回最新的那张
                if(returnTable == null || returnTable.getNo() < table.getNo()){
                    returnTable = table;
                }
            }
        }
        return returnTable;
    }

    private int getUserBanquetCount(long homeUserId){
        if(!cookBoyTableMap.containsKey(homeUserId)){
            return 0;
        }
        return cookBoyTableMap.get(homeUserId).size();
    }

    private int getUserAllJoinCount(long homeUserId){
        if(!cookBoyTableMap.containsKey(homeUserId)){
            return 0;
        }
        int count = 0;
        for(CookBoy3Table cookBoy3Table : cookBoyTableMap.get(homeUserId).values()){
            count += cookBoy3Table.getCookBoy3JoinerMap().size();
        }
        return count;
    }



    public void syncCooker3Table(long serverId,long userId,long homeUserId){
      //  tableCheck();
        CookBoyProto.CookBoy3CookerRespMsg.Builder respMsg = CookBoyProto.CookBoy3CookerRespMsg.newBuilder();
        int ret = 0;
        Map<Long, CookBoyUpUser> syncMap = new ConcurrentHashMap<>();
        if(homeUserId == 0){
            respMsg.setIsSync(false);
            syncMap = cookerMap;
        }else{
            respMsg.setIsSync(true);
            if(cookerMap.containsKey(homeUserId)){
                syncMap.put(cookerMap.get(homeUserId).getUserId(),cookerMap.get(homeUserId));
            }else{
                ret = GameErrorCode.E_COOK_BOY3_USER_NOT_MATCH;
            }
        }
        for(CookBoyUpUser cookBoyUpUser : new ArrayList<>(syncMap.values())){
            CookBoyProto.CookBoy3CookerTempMsg.Builder tempMsg = CookBoyProto.CookBoy3CookerTempMsg.newBuilder();
            tempMsg.setRank(cookBoyUpUser.getRank());
            tempMsg.setUserId(cookBoyUpUser.getUserId());
            CookBoy3Table table = getUserOpenBanquet(cookBoyUpUser.getUserId());
            if(table == null){
                tempMsg.setOpenItemId(0);
                tempMsg.setOpenTime(0);
                tempMsg.setBanquetId(0);
                tempMsg.setCanEat(false);
                tempMsg.setUserNum(0);
            }else{
                tempMsg.setOpenItemId(table.getOpenItemId());
                tempMsg.setOpenTime((int)(table.getOpenTime()/1000));
                tempMsg.setBanquetId(table.getNo());
                tempMsg.setCanEat(!table.getCookBoy3JoinerMap().containsValue(userId));
                tempMsg.setUserNum(table.getCookBoy3JoinerMap().size());
            }
//            tempMsg.setUserNum(getUserAllJoinCount(cookBoyUpUser.getUserId()));
            tempMsg.setBanquetCount(getUserBanquetCount(cookBoyUpUser.getUserId()));
            UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(cookBoyUpUser.getUserId());
            if(userBaseInfo == null){
                continue;
            }
            tempMsg.setUserInfo(PlayerBasePb.parsePlayerBaseTempMsg(userBaseInfo));
            respMsg.addCookerList(tempMsg);
        }
        respMsg.setRet(ret);
        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_COOK_BOY3_GET_TABLE_USER, respMsg);
        MessageHelper.sendPacket(serverId, userId, pbMsg);
    }

    public void timerTask(){
        tableCheck();
        timeSyncTableServer();
        timeSyncBanquetUserServer();

        //活动结束了清掉数据
        long nowTime = System.currentTimeMillis() / 1000;
        if(nowTime >= activityInfo.getEndShowTime() + 5 * 60 && cookBoyTableMap.size() > 0){
            logger.info("阶段三清除活动数据"+getActivityId()+"大小"+cookBoyTableMap.size());
            cookBoyTableMap.clear();
        }

        //内存要炸了就移除不是今天开的宴会吧吧
        /*if(nowTime >= activityInfo.getEndTime() + 10 * 60){
            long todayZeroTimestamp = DateHelper.getTodayZeroTimeStamp();
            for(long userId : cookBoyTableMap.keySet()){
                Map<Integer, CookBoy3Table> tableMap = cookBoyTableMap.get(userId);
                for(CookBoy3Table table : tableMap.values()){
                    if(todayZeroTimestamp != DateHelper.getZeroTimeStamp(table.getOpenTime())){
                        cookBoyTableMap.get(userId).remove(table.getNo());
                    }
                }
            }
        }*/
    }

    public void syncLoginData(long serverId,long userId){
        loginSyncBanquetUser(serverId,userId);
    }

    public void noticeTimerTask(){
        timeSyncBanquetOpenServer();
    }

    private void timeSyncTableServer(){
        //同步宴会参加者的变化给所有区服
        List<CookBoy3Table> list = new ArrayList<>();
        synchronized (syncTableList){
            if(syncTableList.size() > 0){
                list = new ArrayList<>(syncTableList);
                syncTableList.clear();
            }
        }
        if(list.size() > 0){
            syncTableServer(list);
        }
    }

    private void timeSyncBanquetUserServer(){
        synchronized (needSyncCookerList) {
            if(needSyncCookerList.size() > 0){
                CookBoyProto.CookBoy3UserRewardSyncMsg.Builder msg = CrossCookBoyPb.parseCookBoy3UserRewardSyncMsg(getActivityId(),cookerMap,cookBoyTableMap);
                for(long serverId : activityInfo.getServerIdList()){
                    YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_CROSS_COOK_BOY3_BANQUET_USER_DATA_SYNC, msg);
                    MessageHelper.sendPacket(serverId, 0, pbMsg);
                }
                needSyncCookerList.clear();
            }
        }
    }

    private void loginSyncBanquetUser(long serverId,long userId){
          CookBoyProto.CookBoy3UserRewardSyncMsg.Builder msg = CrossCookBoyPb.parseCookBoy3UserRewardSyncMsg(getActivityId(),cookerMap,cookBoyTableMap);
          YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_CROSS_COOK_BOY3_BANQUET_USER_DATA_SYNC, msg);
          MessageHelper.sendPacket(serverId, userId, pbMsg);

          syncCooker3Table(serverId,userId,0);
    }

    //全服广播开宴通知
    private void timeSyncBanquetOpenServer(){
        List<CookBoy3Table> tempList ;
        synchronized (syncOpenList) {
            tempList = new ArrayList<>(syncOpenList);
            syncOpenList.clear();
        }
        if (tempList.isEmpty()) {
            return;
        }

        CookBoyProto.CookBoy3BanquetOpenSyncMsg.Builder msg = CookBoyProto.CookBoy3BanquetOpenSyncMsg.newBuilder();
        msg.setActivityId(getActivityId());
        for(CookBoy3Table cookBoy3Table : tempList){
            CookBoyProto.CookBoy3BanquetOpenTempMsg.Builder banquetMsg = CookBoyProto.CookBoy3BanquetOpenTempMsg.newBuilder();
            banquetMsg.setBanquetId(cookBoy3Table.getNo());
            banquetMsg.setUserId(cookBoy3Table.getUserId());
            banquetMsg.setOpenItemId(cookBoy3Table.getOpenItemId());
            banquetMsg.setOpenTime((int)(cookBoy3Table.getOpenTime()/1000));
            UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(cookBoy3Table.getUserId());
            if(userBaseInfo == null){
                continue;
            }
            banquetMsg.setUserInfo(PlayerBasePb.parsePlayerBaseTempMsg(userBaseInfo));
            msg.addBanquetList(banquetMsg);
        }
        for(long serverId : activityInfo.getServerIdList()){
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_CROSS_COOK_BOY3_OPEN_BANQUET_NOTICE_SYNC, msg);
            MessageHelper.sendPacket(serverId, 0, pbMsg);
        }
    }

    public CrossCookBoy3(ActivityInfo acInfo){
        activityInfo = acInfo;
//		reload();
    }

    public boolean reload() {
        cookBoyTableMap = CrossCookBoyBussiness.getCrossCookBoy3TableMap(activityInfo.getActivityId());
        cookerMap = CrossCookBoyBussiness.getCrossCookBoyUserMap(activityInfo.getActivityId());
        rankToPos();
        return true;
    }

    public boolean save() {
        if(System.currentTimeMillis() < 1629950400000L){
            logger.info("阶段3清除jsonData字符串数据");
            for(Map<Integer, CookBoy3Table> tableMap: cookBoyTableMap.values()){
                for(CookBoy3Table cookBoy3Table : tableMap.values()){
                    cookBoy3Table.getJoinerData();
                }
            }
        }
        List<CookBoy3Table> tempInsertList;
        synchronized (needInsertTableList) {
            tempInsertList = new ArrayList<>(needInsertTableList);
            needInsertTableList.clear();
        }
        if (tempInsertList.size() > 0) {
            CrossCookBoyBussiness.addCrossCookBoy3TableList(tempInsertList);
        }
        List<CookBoy3Table> tempUpdateList;
        synchronized (needUpdateTableList) {
            tempUpdateList = new ArrayList<>(needUpdateTableList);
            needUpdateTableList.clear();
        }
        if (tempUpdateList.size() > 0) {
            CrossCookBoyBussiness.updateCrossCookBoy3TableList(tempUpdateList);
        }
        List<CookBoyUpUser> tempCookBoy2UserInsertList;
        synchronized (needInsertUserList){
            tempCookBoy2UserInsertList = new ArrayList<>(needInsertUserList);
            needInsertUserList.clear();
        }
        if(tempCookBoy2UserInsertList.size() > 0){
            CrossCookBoyBussiness.addCrossCookBoyUserList(tempCookBoy2UserInsertList);
        }
        return true;
    }

    public boolean init() {
        return reload();
    }

    public boolean stop() {
        return false;
    }

    /**
     * 预留接口
     */
    public void repair() {

    }

}
